package com.banciyuan.bcywebview.biz.post;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.util.Log;
import android.view.View;

import com.banciyuan.bcywebview.utils.file.ImageManager;

import java.io.File;
import java.io.FileOutputStream;

/**
 * Created by squall on 2016/1/5.
 */
public class ScreenShots {

    private Activity activity;

    public ScreenShots(Activity activity) {
        this.activity = activity;
    }

    public void saveBitmap(Bitmap bitmap, String name) {
        try {
            File folder = new File(ImageManager.getTemp(activity));
            if (!folder.exists()) {
                folder.mkdirs();
            }
            File imagePath = new File(ImageManager.getTemp(activity) + name);
            if (!imagePath.exists()) {
                imagePath.createNewFile();
            }
            FileOutputStream fos;
            fos = new FileOutputStream(imagePath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            Log.e("GREC", e.getMessage(), e);
        }
    }

    public void saveBitmap(Bitmap bitmap) {
        saveBitmap(bitmap, "screenshot.jpg");
    }

    private Bitmap takeScreenShot() {
        try {
            View view = activity.getWindow().getDecorView().getRootView();
            view.setDrawingCacheEnabled(true);
            view.buildDrawingCache(true);
            Bitmap b1 = Bitmap.createBitmap(view.getDrawingCache());
            view.setDrawingCacheEnabled(false);
            // 获取状态栏高度
            Rect frame = new Rect();
            activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
            int statusBarHeight = frame.top;
            // 获取屏幕长和高
            int width = b1.getWidth();
            int height = b1.getHeight();
            // 去掉标题栏
            float scaleFactor = 6;// 图片缩放比例；
            Matrix matrix = new Matrix();
            matrix.setScale(1 / scaleFactor, 1 / scaleFactor);
            Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight, matrix, true);
            view.destroyDrawingCache();
            return blur(b);
        } catch (Exception e) {
            return null;
        }

    }

    private Bitmap blur(Bitmap bkg) {
        Bitmap overlay = ImageManager.blur(activity, bkg);
        return overlay;
    }

    public void takeShot() {
        saveBitmap(takeScreenShot());
    }
}
